#include "stm32f10x.h"                  // Device header
#include "Delay.h"
#include "Serial.h"
#include "Stepper.h"
#include <string.h>
#include <stdlib.h>

char RxString[100];		//定义用于接收串口字符串的变量

// 解析电机命令的函数
void ParseMotorCommand(char *command)
{
	char *token;
	char motor;
	int angle;
	int speed = 5;  // 默认速度5ms
	
	Serial_Printf("Parsing command: %s\r\n", command);
	
	// 分割字符串，按空格分割
	token = strtok(command, " ");
	
	while (token != NULL)
	{
		Serial_Printf("Token: %s\r\n", token);
		
		// 检查是否是电机标识符 (A 或 B)
		if (strlen(token) == 1 && (token[0] == 'A' || token[0] == 'B'))
		{
			motor = token[0];
			Serial_Printf("Motor: %c\r\n", motor);
			
			// 获取下一个token作为角度
			token = strtok(NULL, " ");
			if (token != NULL)
			{
				Serial_Printf("Angle token: %s\r\n", token);
				// 解析角度值
				angle = atoi(token);
				Serial_Printf("Parsed angle: %d\r\n", angle);
				
				// 根据电机和角度执行相应操作
				if (motor == 'A')
				{
					if (angle > 0)
					{
						Serial_Printf("Motor A Forward %d degrees\r\n", angle);
						Stepper_ForwardAngle(MOTOR_A, angle, speed);
					}
					else if (angle < 0)
					{
						Serial_Printf("Motor A Backward %d degrees\r\n", -angle);
						Stepper_BackwardAngle(MOTOR_A, -angle, speed);
					}
				}
				else if (motor == 'B')
				{
					if (angle > 0)
					{
						Serial_Printf("Motor B Forward %d degrees\r\n", angle);
						Stepper_ForwardAngle(MOTOR_B, angle, speed);
					}
					else if (angle < 0)
					{
						Serial_Printf("Motor B Backward %d degrees\r\n", -angle);
						Stepper_BackwardAngle(MOTOR_B, -angle, speed);
					}
				}
			}
		}
		
		// 获取下一个token
		token = strtok(NULL, " ");
	}
}

int main(void)
{
	/*模块初始化*/
	Serial_Init();		//串口初始化
	Stepper_Init();		//步进电机初始化
	
	/*发送初始化完成信息*/
	Serial_SendString("Dual Stepper Motor Control Ready\r\n");
	Serial_SendString("Command Format: \"A +30 B -60\"\r\n");
	Serial_SendString("A: Motor A, B: Motor B\r\n");
	Serial_SendString("+: Forward, -: Backward\r\n");
	Serial_SendString("Number: Angle in degrees\r\n");
	Serial_SendString("Example: \"A +90 B -45\"\r\n");
	Serial_SendString("Send command and press Enter:\r\n");

	while (1)
	{
		if (Serial_GetStringFlag() == 1)		//检查串口接收字符串的标志位
		{
			Serial_GetString(RxString, sizeof(RxString));		//获取串口接收的字符串
			// 解析并执行电机命令
			ParseMotorCommand(RxString);
			Serial_SendString("OK\n");
		}
		// 处理步进电机运行
		Stepper_Process(MOTOR_A);
		Stepper_Process(MOTOR_B);
		// 添加小延时，避免过于频繁的调用
		Delay_ms(1);
	}
}
